package com.wfh.mianshiji.utils;

import com.wfh.mianshiji.common.ErrorCode;
import com.wfh.mianshiji.config.MinioConfig;
import com.wfh.mianshiji.exception.BusinessException;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @Title: ResumeParseUtil
 * @Author wangfenghuan
 * @Package com.wfh.mianshiji.utils
 * @Date 2025/10/30 20:38
 * @description: 简历解析工具
 */
@Slf4j
@Component
public class ResumeParseUtil {

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfig minioConfig;


    public  String parse(String resumePath){
        // 根据文件类型自动选择合适的解析器
        Parser autoDetectParser = new AutoDetectParser();
        // 用于捕获文档提取的文本内容
        BodyContentHandler bodyContentHandler = new BodyContentHandler(-1);
        ParseContext parseContext = new ParseContext();
        // 文档元数据
        Metadata metadata = new Metadata();

        String content;
        try {
            InputStream inputStream = minioClient.getObject(
                    GetObjectArgs.builder().bucket(minioConfig.getBucket()).object(resumePath).build()
            );
            autoDetectParser.parse(inputStream, bodyContentHandler, metadata, parseContext);
            // 获取文本
            content = bodyContentHandler.toString();
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "简历解析失败");
        }
        // 将换行符转化替换为md文档
        content = content.replaceAll("\\r\\n|\\r|\\n", "#");
        return content;
    }
}
